package gwtgaetools.shared.model;

import gwtgaetools.client.ItemManager;
import gwtgaetools.client.listeners.DeleteListener;
import gwtgaetools.client.ui.IsListable;

import java.util.ArrayList;

public abstract class ObjectManager2<T extends BaseObject2<T>, TT extends ObjectManager2<T, TT>>
	implements IsListable, DeleteListener<TT> {

    public ArrayList<DeleteListener<TT>> deleteListeners = new ArrayList<DeleteListener<TT>>();
    public TT om;

    public ArrayList<ItemManager<String>> keys() {
	ArrayList<ItemManager<String>> out = new ArrayList<ItemManager<String>>();
	out.add(id);
	if (parent() != null)
	    out.addAll(parent().keys());
	return out;
    }

    public ItemManager<Integer> index() {
	return null;
    }

    public ItemManager<String> id = new ItemManager<String>();

    @SuppressWarnings("unchecked")
    public ObjectManager2() {
	om = (TT) this;
    }

    public ObjectManager2(T t) {
	this();
	setItem(t);
    }

    public void setItem(T t) {
	id.setItem(t.getId());
    }

    public ObjectManager2(TT b) {
	this();
	setObservedManager(b);
	b.deleteListeners.add(this);
    }

    @Override
    public ItemManager<String> getListBoxId() {
	return id;
    }

    @Override
    public ItemManager<String> getListBoxName() {
	return id;
    }

    @SuppressWarnings("unchecked")
    public void delete() {
	delete((TT) this);
    }

    @Override
    public void delete(TT t) {
	// if (om != null)
	// om.deleteListeners.remove(this);
	for (DeleteListener<TT> dol : deleteListeners)
	    dol.delete(t);
    }

    public void setObservedManager(TT m) {

	if (om != null)
	    om.deleteListeners.remove(this);

	om = m;

	if (om != null) {
	    om.deleteListeners.add(this);

	    updateFields();

	    id.setObservedManager(m.id);
	} else {

	    id.setObservedManager(null);
	}
    }

    public abstract ObjectManager2<?, ?> parent();

    // field.setObservedManager(m.field) for all fields.
    public abstract void updateFields();

    public boolean sameAs(TT um) {
	if (um == null)
	    return false;
	return sameAs(um.id);
    }

    public boolean sameAs(ItemManager<String> id) {
	if (id == null)
	    return false;
	return sameAs(id.getItem());
    }

    public boolean sameAs(String s) {
	return id.getItem().equals(s);
    }
}
